import type { AxiosResponse } from 'axios';
import { BACKEND_ERROR_CODE, createFlatRequest } from '@sa/axios';
import { useAuthStore } from '@/store/modules/auth';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { getServiceBaseURL } from '@/utils/service';
import { getAuthorization, handleExpiredRequest, showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';

const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);
export const request = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL,
    headers: {
      // apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
    }
  },
  {
    async onRequest(config) {
      const Authorization = getAuthorization();
      const appStore = useAppStore();
      config.headers['Accept-Language'] = appStore.locale;
      Object.assign(config.headers, { Authorization });
      return config;
    },
    isBackendSuccess(response) {
      // 当后端响应代码为“0000”（默认值）时，表示请求成功
      // 要自己更改此逻辑，可以修改.env文件中的VITE_SERVER_SUCCESS_CODE
      const includes = import.meta.env.VITE_SERVICE_SUCCESS_CODE.includes(String(response.data.code));
      if (includes) {
        if (response.data.code % 10 === 1) {
          window.$message?.success(response.data.msg);
        }
      }
      return includes;
    },
    async onBackendFail(response, instance) {

      const authStore = useAuthStore();
      const responseCode = String(response.data.code);

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== response.data.msg);
      }

      // 当后端响应代码位于“logoutCodes”中时，这意味着用户将被注销并重定向到登录页面
      const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];

      if (logoutCodes.includes(responseCode)) {
        handleLogout();
        return null;
      }
      // when the backend response code is in `modalLogoutCodes`, it means the user will be logged out by displaying a modal
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(responseCode) && !request.state.errMsgStack?.includes(response.data.msg)) {
        request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.msg];
        // prevent the user from refreshing the page
        window.addEventListener('beforeunload', handleLogout);

        window.$dialog?.error({
          title: $t('common.error'),
          content: response.data.msg,
          positiveText: $t('common.confirm'),
          maskClosable: false,
          closeOnEsc: false,
          onPositiveClick() {
            logoutAndCleanup();
          },
          onClose() {
            logoutAndCleanup();
          }
        });

        return null;
      }
      // 当后端响应代码为“expiredTokenCodes”时，表示令牌已过期，并刷新令牌
      // api `refreshToken`不能在`expiredTokenCodes`中返回错误代码，否则将是一个死循环，应返回`logoutCodes`或`modalLogoutCodes`
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(responseCode)) {
        const success = await handleExpiredRequest(request.state);
        if (success) {
          const Authorization = getAuthorization();
          Object.assign(response.config.headers, { Authorization });

          return instance.request(response.config) as Promise<AxiosResponse>;
        }
      }

      return null;
    },
    transformBackendResponse(response) {


      return response.data.data;
    },
    onError(error) {
      // 当请求失败时，您可以显示错误消息
      console.log('错误了', error, request.state);
      let message = error.message;
      let backendErrorCode = '';

      // 获取后端错误消息和代码
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.msg || message;
        backendErrorCode = String(error.response?.data?.code || '');
      }
      if (import.meta.env.VITE_SERVICE_ERROR_CODE.includes(backendErrorCode)) {
        // 错误消息不提示
        return;
      }

      // 错误消息显示在模态中
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(backendErrorCode)) {
        return;
      }

      // 当令牌过期时，刷新令牌并重试请求，因此不需要显示错误消息
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(backendErrorCode)) {
        return;
      }
      showErrorMsg(request.state, message);
    }
  }
);

